var express 		= require('express');
var mysql   		= require('mysql');
var config  		= require('../config.json');
var sqlconfig 		= config.mysql;
var router  		= express.Router();
var pool    		= mysql.createPool(sqlconfig);

/*
  Name: data
  Args:
	data:data to be return
	res :response to write data
  Return : 
	Valid String for Client to use
  Description：
	  Return the valid  Data String to client if there is no error
*/

function data(data,res)
{
	console.log("LOG:RESPONSE:"+data);
	return res.end(JSON.stringify({err:0,response:data}));
}

/*
  Name: error
  Args:
	res:response to write err
	err:error message to return
	errcode: description of an error
  Return : 
	Valid String for Client to use
  Description：
	Return the error message to the client 
*/

function error(err,errcode,res)
{
	console.log("LOG:ERROR:"+errcode);
	return res.end(JSON.stringify({err : err,errcode : errcode}));
}

/*
  Name: BeforeAspect 
  Args: 
	request:Object
  Return: 
	data return from this aspect
  Description:
	preprocessor
*/

function BeforeAspect(request)
{
	
	console.log("LOG:REQUEST:"+JSON.stringify(request));
	return request;
}


/*
  Name:Parent_Get_All[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	parent get all communication
*/

function Parent_Get_All(req,res,next)
{
	var query = "SELECT * from communicate where parent_id = ? AND teacher_id = ?;"
	try{
		var args = BeforeAspect(req.body);
		
		if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}

		if(req.session.user_type != 'PARENT')
		{
			error(403,"Permission Denied",res);
			return;
		}

		if(typeof(args['teacher_id']) != 'number'){
        		error(401,"Invalid Argument",res);
			return;		
        	}

		var query_args = [];
		query_args.push(req.session.user['parent_id']);
		query_args.push(args['teacher_id']);
		
		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(300,err,res);
				return;
			}
			else
			{
				data(rows,res);
			}
			return;
		});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}

/*
  Name:Parent_Add_communication[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
	    'parent_id':parent_id
        'communication_type':communication_type
        'communication_content':communication_content
        'communication_time':communication_time'];
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	Add  
*/

function Parent_Add_Communiacate(req,res,next){

	var query = 'insert into communicate set ?;';
	try{

     var args = BeforeAspect(req.body);
		
		if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}

		if(req.session.user_type != 'PARENT')
		{
			error(403,"Permission Denied",res);
			return;
		}
        
        var query_args = {};
      
        if(typeof(args['teacher_id']) != 'number'
        	|| typeof(args['communication_type']) !='number' // database add type in communicate
        	|| typeof(args['communication_content']) !='string'
            || typeof(args['communication_time']) != 'string'){

        	error(401,"Invalid Argument",res);
			return;		
        }

        query_args['teacher_id'] = args['teacher_id'];
        query_args['parent_id'] = req.session.user['parent_id'];
      //  query_args['communication_type'] = args['communication_type'];
        query_args['communication_content'] = args['communication_content'];
        query_args['communication_time'] = args['communication_time'];

        pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else
			{
				data(rows,res);
			}
			return;
		});

	}catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}



/*
  Name:Teacher_Get_All[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	teacher get all communication
*/

function Teacher_Get_All(req,res,next)
{
	var query = "SELECT * from communicate where teacher_id = ? AND parent_id = ?;"
	try{
		var args = BeforeAspect(req.body);
		
		if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}

		if(req.session.user_type != 'TEACHER')
		{
			error(403,"Permission Denied",res);
			return;
		}

		var query_args = [];
		if(typeof(args['parent_id']) != 'number'){

        		error(401,"Invalid Argument",res);
			return;		
        	}

		query_args.push(req.session.user['teacher_id']);
		query_args.push(args['parent_id']);

		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(300,err,res);
				return;
			}
			else
			{
				data(rows,res);
			}
			return;
		});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}

/*
  Name:Teacher_Add_communication[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
	    'parent_id':parent_id
        'communication_type':communication_type
        'communication_content':communication_content
        'communication_time':communication_time'];
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	Add  
*/


function Teacher_Add_Communiacate(req,res,next){

	var query = 'insert into communicate set ?;'
	try{

     var args = BeforeAspect(req.body);
		
		if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}

		if(req.session.user_type != 'TEACHER')
		{
			error(403,"Permission Denied",res);
			return;
		}
        
        var query_args = {};
      
        if(typeof(args['parent_id']) != 'number'
        	|| typeof(args['communication_type']) !='number'
        	|| typeof(args['communication_content']) !='string'
            || typeof(args['communication_time']) != 'string'){

        	error(401,"Invalid Argument",res);
			return;		
        }

        query_args['teacher_id'] = req.session.user['teacher_id'];
        query_args['parent_id'] = args['parent_id'];
  //      query_args['communication_type'] = args['communication_type'];
        query_args['communication_content'] = args['communication_content'];
        query_args['communication_time'] = args['communication_time'];

        pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else
			{
				data(rows,res);
			}
			return;
		});

	}catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}






//Register '/' GET router
router.get('/', function(req, res, next) 
{
  data({},res);
});

//Register all routers 
var functions = {	 "/parent_get_all/"     	: Parent_Get_All
              ,"/parent_add_communication" 	: Parent_Add_Communiacate 
	         , "/tea_get_all/"     	: Teacher_Get_All
   			,"/tea_add_communication" 	: Teacher_Add_Communiacate

			}

for(var i in functions) 
{
	console.log("FUNCTION_LOADED(communication):"+i);
	router.post(i, functions[i]);
}

module.exports = router;
